package com.peng.leetcode.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * GenerateTrees3
 *
 * @author lupeng10
 * @create 2023-10-15 13:31
 */
public class GenerateTrees3 {
    public List<TreeNode> generateTrees(int n) {
        if (n == 0) {
            return new ArrayList<>();
        }
        return build(1, n);
    }

    private List<TreeNode> build(int l, int r) {
        List<TreeNode> ans = new ArrayList<>();
        if (l > r) {
            ans.add(null);
            return ans;
        }
        for (int i = l; i <= r; i++) {
            List<TreeNode> l1 = build(l, i - 1);
            List<TreeNode> l2 = build(i + 1, r);
            for (TreeNode ln : l1) {
                for (TreeNode rn : l2) {
                    TreeNode root = new TreeNode(i);
                    root.left = ln;
                    root.right = rn;
                    ans.add(root);
                }
            }
        }
        return ans;
    }
}
